<!-- 这个组件用于个人主页模块的已发布文章修改功能 -->
<template>
  <div id='box' :style="{ width: width }">

    <!-- 菜单栏 -->
    <Toolbar id="editor-toolbar" :editor="editor" :defaultConfig="toolbarConfig" :mode="mode" />
    <div id="content" :style="{ height: height }" @mousewheel="scrollChange">
      <div id="editor-container" :style="{ width: editorWidth }">
        <!-- 标题 -->
        <div id="title-container">
          <input placeholder="请输入标题..." v-model="input_title" />
        </div>
        <!-- 编辑框/正文 -->
        <Editor id="editor-text-area" v-model="html" :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated"
          :style="{ 'min-height': editorHeight }" />
      </div>

      <!-- 发布设置：主题、封面、摘要 v-show='publish'-->
      <div id='publish-container' :style="{ width: editorWidth }" v-show='publish'>
        <div id='subject-radio'>
          <div style='margin-left: 8px; white-space:nowrap; '>文章主题：</div>
          <div id='radio-group'>
            <el-radio-group v-model="subject" size='small'>
              <el-radio-button v-for="item in subjectList" :key='item.subject_id' :label="item.subject_id" style="margin-left: 12px">
                {{ item.name }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div id='cover-upload' style="margin-bottom: 20px">
          <span style='margin-left: 8px'>文章封面：</span>
          <el-upload action="#" :multiple='false' :auto-upload='false' list-type="picture-card" :limit='1' :file-list="coverList"
            style="display: inline-block;" :class="{ hideUploadBtn: noneUploadBtn }" :on-change='coverChange' :on-remove='coverRemove'>
            <i slot="default" class="el-icon-plus"></i>
          </el-upload>
        </div>
        <div id='abstract-input'>
          <span style='color: #fc5531'>*</span>
          <span class="text">编辑摘要：</span>
          <el-input type='textarea' v-model="abstract" maxlength="200" show-word-limit :rows='6'></el-input>
        </div>
      </div>
    </div>

    <!-- 顶部按钮：路由跳转 -->
    <div id='back' @click="goback">返回
      <i class="iconfont icon-back" />
    </div>

    <!-- 底部按钮 v-show='publish'-->
    <div id='footer' :style="{ width: width }" v-show='publish'>
      <div id='footer-container' :style="{ width: editorWidth }">
        <div>
          <el-button class="toBtn" @click="jump" v-if='toTop' type="text">回到顶部
            <i class="el-icon-arrow-up" />
          </el-button>
          <el-button class="toBtn" @click="jump" v-else type="text">发文设置
            <i class="el-icon-arrow-down" />
          </el-button>
        </div>
        <div>
          <el-button class="pubBtn" @click="cancel">取消
          </el-button>
          <el-button class="pubBtn" @click="publishBlog" type="info">保存修改
          </el-button>
        </div>
      </div>
    </div>

  </div>
</template>
  
<script>
import Vue from 'vue'
import { Editor,Toolbar } from '@wangeditor/editor-for-vue'
import { Message } from "element-ui";
import articleApi from '@/api/article.js'

export default Vue.extend({
  props: {
    width: {
      type: String,
      default: "100%",  //组件的宽度
    },
    height: {
      type: String,
      default: "928px", //组件的高度
    },
    editorWidth: {
      type: String,
      default: "900px",  //编辑框的宽度
    },
    editorHeight: {
      type: String,
      default: "900px",  //编辑框的高度
    },
    title: {
      type: String,
      default: "",  //修改文章时传入：获取文章标题进行展示
    },
    content: {
      type: String,
      default: "",  //修改文章时传入：获取文章内容进行展示
    },
    article_id: {
      type: String,
      default: ''
    },
    /*
    * 以下参数与发布设置div有关
    */
    publish: {
      type: Boolean,
      default: false, //控制 发布设置div、发布按钮 是否显示
    },
    ediotType: {
      type: String,
      default: "",  //'create' or 'update', 暂未使用, 可以标识是 写文章/修改文章 页面
    },
  },
  components: { Editor,Toolbar },
  data() {
    return {
      editor: null,
      html: '',           //父组件获取文章内容
      input_title: '',    //父组件获取标题内容
      //菜单栏的配置
      toolbarConfig: {
        insertKeys: {
          index: 9,
          keys: ['clearStyle']
        },
        excludeKeys: [
          'group-more-style',
          'group-video',
          "insertTable",
          "codeBlock",
          "divider",
          "fullScreen"
        ]
      },
      //编辑框的配置
      editorConfig: {
        placeholder: '请输入内容...',
        customAlert: (s,t) => {
          switch(t) {
            case 'success':
              Message.success(s)
              break
            case 'info':
              Message.info(s)
              break
            case 'warning':
              Message.warning(s)
              break
            case 'error':
              Message.error(s)
              break
            default:
              Message.info(s)
              break
          }
        },
        //上传图片的配置
        MENU_CONF: {
          'uploadImage': {
            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 10*1024*1024, // 10M
            // 小于该值就插入 base64 格式（而不上传），默认为 0
            base64LimitSize: 10*1024*1024// 10M
          }
        }
      },
      //模式
      mode: 'default', // or 'simple'
      observer: null,
      //发文设置相关
      jumpname: '发文设置',
      toTop: false,
      subjectList: [],
      subject: '',
      coverList: [],
      noneUploadBtn: false,
      abstract: '',
    }
  },
  watch: {
    // 监听到父组件传递过来的数据
    content(newData,oldData) {
      this.editor.setHtml(newData)
    },
    title(newData,oldData) {
      this.input_title=this.title
    }
  },
  methods: {
    async onCreated(editor) {
      this.editor=Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
      // 点击空白处 focus 编辑器
      document.getElementById('editor-text-area').addEventListener('click',e => {
        if(e.target.id==='editor-text-area') {
          this.editor.blur()
          this.editor.focus(true) // focus 到末尾
        }
      })
      //编辑框高度自动增长 - 监听编辑框高度改变 - this.handleResize
      const dom=document.getElementById("editor-text-area");
      const scrollview=document.getElementById("content")
      scrollview.addEventListener('scroll',this.scrollChange,true)
      //获取主题列表
      if(this.publish) {
        await this.getSubject();
      }
      //old value
      if(this.$route.query.abstract) this.abstract=this.$route.query.abstract
      if(this.$route.query.cover) {
        this.coverList.push({ name: '',url: this.$route.query.cover })
        this.noneUploadBtn=true
      }
      if(this.$route.query.subject) this.subject=this.$route.query.subject
    },

    //监听编辑框高度改变 - ,
    handleResize() {
      const height=document.getElementById("editor-text-area").offsetHeight //编辑框当前高度
      const min_height=Number(this.editorHeight.substring(0,this.editorHeight.indexOf('p'))); //编辑框初始高度
      //文章编辑框高度超出初始值时
      if(height>min_height) {
        const content=document.getElementById('content');
        const editor_container=document.getElementById("editor-container")
        //scroll定位到文末
        content.scrollTo({
          top: editor_container.offsetTop+editor_container.offsetHeight-min_height,//需要父元素设置postion(relative、absolute、fixed)
          behavior: "smooth"
        })
      }
    },

    //监听scroll
    scrollChange() {
      const div=document.getElementById('content');
      const editor_container=document.getElementById("editor-container")
      const min_height=Number(this.editorHeight.substring(0,this.editorHeight.indexOf('p'))); //编辑框初始高度
      if(div.scrollTop>=editor_container.offsetTop+editor_container.offsetHeight-min_height) this.toTop=true //回到顶部
      else this.toTop=false //发布设置
    },

    //返回上一页按钮
    goback() {
      this.$router.push({
        name: '个人中心-文章展示',
      })
    },

    //回到顶部 or 回到底部 按钮
    jump() {
      const div=document.getElementById('content');
      if(this.toTop) {
        div.scrollTo({
          top: 0,
          behavior: "smooth"
        })
      } else {
        div.scrollTo({
          top: div.scrollHeight,
          behavior: "smooth"
        })
      }
    },

    //消息弹框
    message(text,type,offset) {
      this.$notify({
        title: '提示',
        message: text,
        type: type,
        duration: 1500,
        offset: offset,
        showClose: false
      })
    },

    //发布文章 按钮
    async publishBlog() {
      //判断
      if(this.input_title==null||this.input_title.trim()=='') {
        this.message('标题不能为空','error',160)
        return
      }
      if(this.editor.isEmpty()) {
        this.message('正文不能为空','error',160)
        return
      }
      if(this.abstract==null||this.abstract.trim()=='') {
        this.message('摘要不能为空','error',160)
        return
      }
      //数据
      let data={}
      data.article_id=this.article_id;
      data.title=this.input_title;
      data.content=this.html;
      data.abstract=this.abstract;
      data.state=0;
      if(this.coverList!=null&&this.coverList.length==1) data.cover=this.coverList[0].raw;
      if(this.subject!=null&&this.subject!='') data.subject_id=this.subject;
      //接口
      const article=await articleApi.updateArticle(data)
      //跳转
      this.$router.push({
        name: '个人中心-文章展示',
      })
    },

    //保存草稿 按钮
    async cancel() {
      //跳转
      this.$router.push({
        name: '个人中心-文章展示',
      })
    },
    //获取文章主题列表
    async getSubject() {
      this.subjectList=(await articleApi.getSubject()).data;
    },

    //文件列表移除文件时的钩子, 添加文件时会被调用
    coverChange(file,fileList) {
      this.noneUploadBtn=fileList.length==1
      this.coverList=fileList
    },

    //文件列表移除文件时的钩子
    coverRemove(file,fileList) {
      this.noneUploadBtn=fileList.length==1
      this.coverList=fileList
    },

  },
  beforeDestroy() {
    const editor=this.editor
    if(editor==null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
})
</script>
    
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style src="./theme.css"></style>
<style lang='scss' scoped>
#box {
  position: relative;
}

#title-container {
  padding: 20px 0;
  border-bottom: 1px solid #e8e8e8;
}

#title-container input {
  font-size: 30px;
  border: 0;
  outline: none;
  width: 100%;
  line-height: 1;
  color: #fefefe;
  background-color: transparent;
}

#editor-toolbar {
  display: flex;
  justify-content: space-around;
  width: 100%;
  background-color: rgba(34, 52, 87, 0.6);
  margin: 0 auto;

  ::v-deep .w-e-select-list {
    &::-webkit-scrollbar {
      width: 8px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #1f3964;
      border-radius: 8px;
    }
  }

  ::v-deep .w-e-menu-tooltip-v5:before,
  ::v-deep .w-e-menu-tooltip-v5:after {
    content: none;
  }
}

#content {
  background-color: rgba(34, 52, 87, 0.6);
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;

  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #1f3964;
    border-radius: 8px;
  }
}

#editor-container {
  margin: 30px auto 20px auto;
  background-color: rgba(34, 52, 87, 0.8);
  padding: 20px 50px 50px 50px;
  border: 1px solid rgba(34, 52, 87, 0.8);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgb(0 0 0 / 12%);
}

#editor-text-area {
  margin-top: 20px;

  ::v-deep .w-e-menu-tooltip-v5:before,
  ::v-deep .w-e-menu-tooltip-v5:after {
    content: none;
  }

  ::v-deep .w-e-modal {
    background-color: rgba(34, 52, 87, 1);

    input[type="number"],
    input[type="text"],
    textarea {
      background-color: #1f3964;
      border: 1px solid #1f3964;
    }
  }
}

::v-deep .w-e-hover-bar {
  display: none;
}

#back {
  position: absolute;
  top: 10px;
  left: 20px;
  font-family: Tahoma, Helvetica, Arial, "宋体", sans-serif;
  color: #67a1e5;
  text-shadow: 0 0 4px #67a1e5;
  user-select: none;
  cursor: pointer;
}

#publish-container {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  margin: 10px auto 80px auto;
  padding: 20px 50px 20px 40px;
  background-color: rgba(34, 52, 87, 0.8);
  border: 1px solid rgba(34, 52, 87, 0.8);
  border-radius: 8px;
  user-select: none;
  font-size: 16px;
}

#subject-radio {
  display: flex;
}

#radio-group {
  margin-bottom: 20px;

  ::v-deep .el-radio-button__inner {
    margin-right: 10px;
    margin-top: 10px;
    border: 1px solid #1e75a4;
    border-radius: 4px !important;
    font-size: 16px;
  }

  ::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    color: #1e537b;
    background-color: rgba(93, 161, 229, 1);
    border: #67a1e5;
  }

  ::v-deep .el-radio-group {
    margin-top: -10px;
  }
}

#cover-upload {
  //回显图片
  ::v-deep .el-upload-list--picture-card {
    margin-left: 14px;
  }

  //上传按钮
  ::v-deep .el-upload--picture-card {
    background-color: rgba(30, 117, 164, 0.5);
    border: 1px dashed #1e75a4;
  }

  ::v-deep .hideUploadBtn .el-upload--picture-card {
    display: none;
  }
}

#abstract-input {
  display: flex;
  justify-content: flex-start;

  .text {
    width: 136px;
  }

  ::v-deep .el-textarea {
    width: 680px;
    margin-left: -40px;
    font-size: 16px;
  }
}

#footer {
  height: 60px;
  position: absolute;
  bottom: 0;
  z-index: 20000;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(34, 52, 87, 1);
  user-select: none;
}

#footer-container {
  display: flex;
  justify-content: space-between;
  align-items: center;

  ::v-deep .toBtn {
    font-size: 16px;
    color: #757575;
  }

  ::v-deep .pubBtn {
    font-size: 18px;
    border-radius: 20px;
  }
}
</style>
  
   
  